#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);

  setWindowTitle("TCP客户端(方式二)");
  // 2
  m_thread.start();

  // 3，调用moveToThread将对象移动至线程中
  m_taskWorker.moveToThread(&m_thread);
  qDebug() << "QThread对象的地址" << &m_thread;

  // 连接信号槽
  connect(this, &Widget::onConnect, &m_taskWorker, &TaskWorker::onConnect);
  connect(this, &Widget::onSend, &m_taskWorker, &TaskWorker::onSend);
  connect(this, &Widget::onClose, &m_taskWorker, &TaskWorker::onClose);

  connect(&m_taskWorker, &TaskWorker::showMessage, this, &Widget::showMessage);
}

Widget::~Widget() {
  // 关闭套接字
  emit onClose();
  // quit退出线程的消息循环
  m_thread.quit();
  // 等待线程结束
  m_thread.wait();
  qDebug() << "线程退出了！";

  delete ui;
}

void Widget::on_btnConnect_clicked() {
  if (!m_connected) {
    QString ip = ui->lineEditIP->text();
    uint port = ui->lineEditPort->text().toUInt();
    // 去触发 线程中的TcpSocket对象的槽函数
    emit onConnect(ip, port);

  } else {
    // 断开与服务器的连接
    emit onClose();
  }
}

void Widget::showMessage(const QString &info, bool conn) {
  ui->messageShoxEdit->appendPlainText(info);
  m_connected = conn;
  if (conn) {
    ui->btnConnect->setText("断开");
  } else {
    ui->btnConnect->setText("连接");
  }
}

void Widget::on_btnSend_clicked() {
  QString msg = ui->messageEdit->text();

  // 注意字符编码，需要保持一致
  QByteArray data = msg.toUtf8();
  // 给服务端发送数据
  emit onSend(data);
}
